import { useAPIUtils } from "@/components/APIUtilsProvider";
import ImageModal from "@/components/ImageModal";
import { moreModals } from "@/components/moreModals";
import PageLayout from "@/components/PageLayout";
import RenderIf from "@/components/RenderIf";
import UserPill from "@/components/UserPill";
import When from "@/components/When";
import {
  Box,
  Button,
  Flex,
  Grid,
  Group,
  Space,
  Stack,
  Text,
  Title,
} from "@mantine/core";
import dayjs from "dayjs";
import { useParams } from "react-router-dom";
import StatusRenderer from "./StatusRenderer";

export default function ApplicationDetails() {
  const { id, role } = useParams();
  const { pageTitle } = getPageMeta({ role });

  return (
    <PageLayout title={pageTitle}>
      <Grid w="96%">
        <Grid.Col span={8}>
          <Basics />
        </Grid.Col>
        <Grid.Col span={3} offset={1}>
          <ApplicationAttacthments targbetRole={role} />
        </Grid.Col>
      </Grid>
    </PageLayout>
  );
}

const Descriptions = ({ title, data, tools }) => {
  return (
    <Box padding="md">
      {title && (
        <Flex justify={"space-between"} align={"baseline"}>
          <Title order={6} mb={"lg"}>
            {title}
          </Title>
          <Space />
          {tools}
        </Flex>
      )}
      <Grid gutter="0" style={{ border: "0.1px solid rgba(0, 0, 0, 0.1)" }}>
        {data.map((item, index) => (
          <>
            <Grid.Col
              span={2}
              bg={"gray.1"}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text weight={100} size="sm">
                {item.label}
              </Text>
            </Grid.Col>
            <Grid.Col
              span={item.block ? 10 : 4}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text>{item.value}</Text>
            </Grid.Col>
          </>
        ))}
      </Grid>
    </Box>
  );
};

function Basics() {
  const { id, role } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const query = tanstackQuery(`/api/admin/${role}/applications/${id}`);

  const decide = async (id, action, comment) => {
    await restPUT(
      `/api/admin/${role}/applications/${id}?action=${action}&comment=${comment}`
    );
    tanstackInvalidate(`/api/admin/${role}/applications`);
    tanstackInvalidate(`/api/admin/${role}/applications/${id}`);
  };

  if (!query.data) {
    return <></>;
  }

  const application = query.data;

  const tools = (
    <Group gap="sm">
      <RenderIf auth="QualificationApproval">
        <Button
          size="xs"
          onClick={() =>
            moreModals.openDefaultConfirmModal({
              title: "确定要通过吗？",
              onConfirm: () => {
                decide(application.id, "APPROVE");
              },
            })
          }
          disabled={application.status !== "PENDING"}
        >
          同意
        </Button>
        <Button
          color="red.7"
          size="xs"
          onClick={() =>
            moreModals.openPromptModal({
              title: "请填写审批意见(拒绝原因)",
              onConfirm: (comment) => {
                decide(application.id, "REJECT", comment);
              },
            })
          }
          disabled={application.status !== "PENDING"}
        >
          拒绝
        </Button>
      </RenderIf>
    </Group>
  );

  const descriptionsData = [
    {
      label: "申请人",
      value: <UserPill user={application.applicant} />,
    },
    {
      label: "状态",
      value: <StatusRenderer status={application.status} />,
    },
    {
      label: "申请时间",
      value: dayjs(application.createdAt).format("YYYY/MM/DD HH:mm:ss"),
      block: true,
    },
    {
      label: "审批时间",
      value:
        application.decidedAt &&
        dayjs(application.decidedAt).format("YYYY/MM/DD HH:mm:ss"),
    },
    {
      label: "审批人",
      value: <UserPill user={application.decidedBy} />,
    },
    {
      label: "审批意见",
      value: application.comment,
      block: true,
    },
  ];
  return (
    <Descriptions
      title={`业务流水号: ${id}`}
      data={descriptionsData}
      tools={tools}
    />
  );
}

function ApplicationAttacthments({ targbetRole }) {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const query = tanstackQuery(`/api/admin/${targbetRole}/applications/${id}`);

  if (!query.data) {
    return <></>;
  }

  const application = query.data;

  return (
    <>
      <Title order={6} mb={"lg"}>
        附件
      </Title>
      <Stack>
        <Text c={"dimmed"}>协议同意签名</Text>
        <ImageModal src={application.signatureUrl} />

        <When condition={targbetRole == "AG_WHS"}>
          <Text c={"dimmed"}>营业执照（图片）</Text>
          <ImageModal src={application.meta.licenseUrl} />
        </When>
        <When>
          <When condition={targbetRole == "MANAGER"}></When>
          <Text c={"dimmed"}>合约（图片）</Text>
          <ImageModal src={application.meta.contract} />
        </When>
      </Stack>
    </>
  );
}

function getPageMeta({ role }) {
  let pageTitle = "???";

  switch (role) {
    case "AG_SHOP":
      pageTitle = "开店申请详情";
      break;
    case "AG_WHS":
      pageTitle = "批发商资质申请详情";
      break;
    case "AG_AGENT":
      pageTitle = "代理商资质申请详情";
      break;
    case "MANAGER":
      pageTitle = "业务经理资质申请详情";
      break;
  }

  return { pageTitle };
}
